import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {User, UserManage} from '../entity/user.model';
import {Observable} from 'rxjs/Observable';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class UserService {
  private readonly param = 'sysUsers';

  private get url(): string {

    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }


  constructor(private http: InterceptorService) {

  }


  /**
   * 获取所有的用户
   *
   * @returns {Promise<UserManage[]>}
   * @memberof UserService
   */
  getUsers(): Promise<User[]> {
    return this.http.get(`${this.url}/userProfile`)
      .toPromise()
      .then(res => res.code === '200' ? res.data as User[] : [])
      .catch(this.handleError);
  }

  /**
   * 根据companyId获取用户
   *
   * @returns {Promise<UserManage[]>}
   * @memberof UserService
   */
  getUsersByCompanyId(companyId: number): Promise<User[]> {
    return this.http.get(`${this.url}/companyId/${companyId}`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as UserManage : [])
      .catch(this.handleError);
  }

  /**
   * 根据userId获取用户详细信息
   *
   * @param {number} userId
   * @returns {Promise<UserManage>}
   * @memberof UserService
   */

  //   public getUsersByuserId(userId: number): Promise<{ user:User; userProfile: UserProfile; userFarmVOList: UserFarm[] }> {
  //   return this.http.get(`${this.url}/userVO/${userId}`)
  //     .toPromise()
  //     .then(response => {
  //       return response.data;
  //     })
  //     .catch(this.handleError);
  // }
  getUsersByuserId(userId: number): Promise<UserManage> {
    return this.http.get(`${this.url}/userVO/${userId}`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as UserManage : [])
      .catch(this.handleError);
  }

  /**
   * 新增
   *
   * @param {UserManage} userManage
   * @returns {Promise<UserManage>}
   * @memberof UserService
   */
  create(userManage: UserManage): Promise<UserManage> {
    const url = `${this.url}/saveUserVO`;
    return this.http.post(url, JSON.stringify(userManage))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as UserManage;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }


  /**
   * 更新
   *
   * @param {UserManage} userManage
   * @returns {Promise<UserManage>}
   * @memberof UserService
   */
  update(userManage: UserManage): Promise<UserManage> {
    const url = `${this.url}/userVO`;
    return this.http.put(url, JSON.stringify(userManage))
      .toPromise()
      .then(() => userManage)
      .catch(this.handleError);
  }

  myUpdate(userManage: UserManage): Promise<UserManage> {
    const url = `${this.url}/updateUserVO`;
    return this.http.post(url, JSON.stringify(userManage))
      .toPromise()
      .then(() => userManage)
      .catch(this.handleError);
  }


  /**
   * 删除
   *
   * @param {number} id
   * @returns {Promise<void>}
   * @memberof UserService
   */
  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(userIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${userIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  //判断UserName是否已经存在
  hasUserName(userName: string, userId: number): Observable<boolean> {
    // const url = `http://192.168.15.63:8585/webapi/v1/sysUsers/userName/${userName}/userId/${userId}`;
    const url = `${this.url}/userName/${userName}/userId/${userId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }


}


// WEBPACK FOOTER //
// ./src/app/service/user.service.ts
